package com.java.netty.tcpprotocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;


//处理业务的handler
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        //接收到数据，并处理
        System.out.println("服务器接收到信息序号:" + (++this.count));
        System.out.println("服务器接收到信息长度:" + msg.getLen());
        System.out.println("服务器接收到信息内容:" + new String(msg.getContent(), CharsetUtil.UTF_8));

        //回复消息
        String uuid = UUID.randomUUID().toString();
        byte[] content = uuid.getBytes(CharsetUtil.UTF_8);
        int length = content.length;
        ctx.writeAndFlush(new MessageProtocol(length, content));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
